package com.wf.netty.echoaction;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Scanner;

/**
 * 功能描述
 *
 * @author wf
 * @since 2022/5/26
 */
public class NettyEchoClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(NettyEchoClient.class);

    private void run() {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline().addLast(NettyEchoClientHandler.INSTANCE);
                        }
                    });
            ChannelFuture future = bootstrap.connect(new InetSocketAddress(8888)).sync();
            future.addListener((ChannelFutureListener) future1 -> {
                if (future1.isSuccess()) {
                    LOGGER.info("EchoClient客户端连接成功!");
                } else {
                    LOGGER.info("EchoClient客户端连接失败!");
                }
            });

            //阻塞，直到连接成功
            future.sync();
            Channel channel = future.channel();
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入发送内容:");
            while (scanner.hasNext()) {
                //获取输入的内容lll
                String next = scanner.next();
                byte[] bytes = (new Date() + " >>"
                        + next).getBytes(StandardCharsets.UTF_8);
                //发送ByteBuf
                ByteBuf buffer = channel.alloc().buffer();
                buffer.writeBytes(bytes);
                channel.writeAndFlush(buffer);
                System.out.println("请输入发送内容:");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅关闭EventLoopGroup，
            //释放掉所有资源，包括创建的线程
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new NettyEchoClient().run();
    }
}
